console.log('Auth.js loaded:', new Date().toISOString());

// 认证相关的 API 调用
const auth = {
    // 登录
    async login(username, password) {
        try {
            console.log('Starting login process for:', username);
            
            // 1. 登录获取 token
            let loginResponse;
            try {
                // 修改请求格式，使用 FormData
                const formData = new URLSearchParams();
                formData.append('username', username);
                formData.append('password', password);
                
                loginResponse = await window.apiClient.post('/api/auth/login', formData, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });
                
                console.log('Raw login response:', loginResponse);
            } catch (loginError) {
                console.error('Login request failed:', {
                    error: loginError.message,
                    response: loginError.response?.data,
                    status: loginError.response?.status,
                    data: loginError.response?.data
                });
                // 防止错误时立即跳转
                await new Promise(resolve => setTimeout(resolve, 2000));
                throw loginError;
            }

            if (!loginResponse?.data?.access_token) {
                console.error('Invalid login response:', loginResponse?.data);
                await new Promise(resolve => setTimeout(resolve, 2000));
                throw new Error('Login response missing access_token');
            }

            // 打印完整的登录响应
            console.log('Login successful, token received:', {
                token_preview: loginResponse.data.access_token.substring(0, 20) + '...',
                full_token: loginResponse.data.access_token,
                token_type: loginResponse.data.token_type
            });
            
            // 2. 保存 token
            const authData = {
                access_token: loginResponse.data.access_token,
                token_type: 'Bearer',
                username: username
            };
            
            console.log('Saving auth data to localStorage:', {
                ...authData,
                token_preview: authData.access_token.substring(0, 20) + '...'
            });
            
            try {
                localStorage.setItem(API_CONFIG.USER_KEY, JSON.stringify(authData));
                console.log('Auth data saved successfully');
                // 添加延迟确保数据保存
                await new Promise(resolve => setTimeout(resolve, 500));
            } catch (storageError) {
                console.error('Failed to save auth data:', storageError);
                throw storageError;
            }
            
            // 3. 获取用户信息
            console.log('Preparing /me request with token:', {
                token_preview: authData.access_token.substring(0, 20) + '...',
                auth_header: `Bearer ${authData.access_token}`
            });
            
            let meResponse;
            try {
                meResponse = await window.apiClient.get('/api/auth/me', {
                    headers: {
                        'Authorization': `Bearer ${authData.access_token}`,
                        'Accept': 'application/json'
                    }
                });
                console.log('User info received:', meResponse.data);
            } catch (meError) {
                console.error('Failed to get user info:', {
                    error: meError.message,
                    response: meError.response?.data,
                    status: meError.response?.status,
                    headers: meError.config?.headers
                });
                // 防止错误时立即跳转
                await new Promise(resolve => setTimeout(resolve, 2000));
                throw meError;
            }
            
            // 4. 合并用户数据
            const userData = {
                ...authData,
                ...meResponse.data
            };
            
            console.log('Final user data:', {
                ...userData,
                token_preview: userData.access_token.substring(0, 20) + '...'
            });
            
            localStorage.setItem(API_CONFIG.USER_KEY, JSON.stringify(userData));
            
            // 添加延迟确保数据保存和日志显示
            await new Promise(resolve => setTimeout(resolve, 1000));
            return userData;
        } catch (error) {
            console.error('Login process failed:', {
                error: error.message,
                type: error.constructor.name,
                stack: error.stack,
                response: error.response?.data
            });
            // 防止错误时立即跳转
            await new Promise(resolve => setTimeout(resolve, 2000));
            throw error;
        }
    },

    // 获取当前用户信息
    async getCurrentUser() {
        try {
            const response = await window.apiClient.get('/api/auth/me');
            console.log('User info:', response.data); // 调试用
            return response.data;
        } catch (error) {
            console.error('Get user info error:', error.response?.data || error.message);
            throw error;
        }
    },

    // 登出
    logout() {
        console.log('Auth logout called');
        localStorage.removeItem(API_CONFIG.USER_KEY);
        localStorage.removeItem(API_CONFIG.TOKEN_KEY);
        console.log('Storage cleared, redirecting to login page');
        window.location.replace(`${API_CONFIG.BASE_URL}/login.html`);
    },

    // 检查是否已登录
    isAuthenticated() {
        try {
            const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
            console.log('Checking auth status:', {
                hasUserStr: !!userStr
            });
            
            if (!userStr) return false;
            
            const user = JSON.parse(userStr);
            const isValid = !!user.access_token;
            
            console.log('Auth check result:', {
                hasToken: isValid,
                username: user.username
            });
            
            return isValid;
        } catch (e) {
            console.error('Auth check failed:', e);
            return false;
        }
    },

    // 获取存储的用户信息
    getUser() {
        const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
        return userStr ? JSON.parse(userStr) : null;
    }
};

window.auth = auth; 